// pages/home/home.js
Page({
    data: {
        courses: [],
        searchResult: [],
        categories: [],
        selectedCategory: null,
        selectedCourse: null // Add this to store the selected course
    },
    onLoad() {
        this.checkLoginStatus();
        if (!this.data.userId) {
            // 如果用户未登录，导航到 login 页面
            wx.navigateTo({
                url: '/pages/login/login'
            });
        } else {
            this.getCategories(); // 页面加载时只获取类别数据
        }
    },
    checkLoginStatus() {
        const userId = wx.getStorageSync('userId');
        if (userId) {
            this.setData({
                userId: userId
            });
        }
    },
    getCategories: function() {
        wx.request({
            url: 'http://127.0.0.1:5000/api/course_categories',
            method: 'GET',
            success: (res) => {
                this.setData({
                    categories: res.data
                });
            },
            fail: (err) => {
                wx.showToast({
                    title: '获取分类失败',
                    icon: 'none'
                });
            }
        });
    },
    getCourses: function(category) {
        const userId = this.getUserId(); // 获取用户ID
        const data = category ? { category_id: category.id } : {}; // 确保传递正确的参数
        data.user_id= userId;
        wx.request({
            url: 'http://127.0.0.1:5000/api/courses',
            method: 'GET',
            data: data,
            success: (res) => {
                console.log('Courses fetched successfully:', res.data); // 调试信息
                this.setData({
                    courses: res.data
                });
            },
            fail: (err) => {
                console.error('Failed to fetch courses:', err); // 调试信息
                wx.showToast({
                    title: '获取课程失败',
                    icon: 'none'
                });
            }
        });
    },
    createOrder: function(event) {
        const course = event.currentTarget.dataset.course;
        // Call the createOrder function with the course data
        this.setData({
            selectedCourse: course // Store the selected course
        });
        this.callCreateOrder(course).then(paymentInfo => {
            if (paymentInfo) {
                // Navigate to the payment page
                wx.requestPayment({
                    provider: 'wxpay', // 表明使用微信支付
                    timeStamp: paymentInfo.result.timeStamp, // 时间戳
                    nonceStr: paymentInfo.result.nonceStr, // 随机字符串
                    package: paymentInfo.result.package, // 统一下单接口返回的 prepay_id 与 prepay_id= 组成的字符串
                    signType: paymentInfo.result.signType, // 签名类型，如 MD5 或 HMAC - SHA256
                    paySign: paymentInfo.result.paySign, // 签名
                    success: function (res) {
                        // 支付成功后的处理逻辑
                        wx.showToast({ title: '支付成功' })
                    },
                    fail: function (err) {
                        // 支付失败后的处理逻辑
                        console.error('Payment failed:', err);
                        wx.showToast({ title: '支付失败'})
                    }
                });
                // uni.navigateTo({
                //     url: '/pages/payment/payment?paymentInfo=' + encodeURIComponent(JSON.stringify(paymentInfo))
                // });
            } else {
                console.error('Failed to create order');
                this.setData({
                    errorMessage: '创建订单失败'
                });
                wx.showToast({
                    title: '创建订单失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        }).catch(error => {
            console.error('Error creating order:', error);
            this.setData({
                errorMessage: '创建订单失败'
            });
            wx.showToast({
                title: '创建订单失败',
                icon: 'none',
                duration: 2000
            });
        });
    },
    callCreateOrder: function(course) {
        return new Promise((resolve, reject) => {
            const userId = this.getUserId(); // 获取用户ID
            if (!userId) {
                reject(new Error('用户ID未找到'));
                return;
            }

            const orderData = {
                user_id: userId,
                course_id: course.id,
                order_name: course.title, // 使用课程标题作为订单名称
                order_status: 1 // 假设1表示待支付状态
            };

            wx.request({
                url: 'http://127.0.0.1:5000/api/order',
                method: 'PUT',
                data: orderData,
                header: {
                    'content-type': 'application/json'
                },
                success: (res) => {
                    if (res.statusCode === 201) {
                        console.log('Order created successfully:', res.data);
                        const paymentInfo = res.data.payment_info;
                        resolve(paymentInfo);
                    } else {
                        console.error('Order creation failed:', res.data);
                        reject(new Error('Order creation failed'));
                    }
                },
                fail: (err) => {
                    console.error('Order creation failed:', err);
                    reject(new Error('Order creation failed'));
                }
            });
        });
        },
        
        processPayment(paymentInfo) {
        // 假设这里调用微信支付接口
        wx.requestPayment({
            timeStamp: paymentInfo.timeStamp,
            nonceStr: paymentInfo.nonceStr,
            package: paymentInfo.package,
            signType: paymentInfo.signType,
            paySign: paymentInfo.paySign,
            success: (res) => {
                console.log('支付成功:', res);
                this.setData({
                    paymentInfo: '支付成功'
                });
                this.goToCourseDetails({ currentTarget: { dataset: { course: this.data.selectedCourse } } });
            },
            fail: (err) => {
                console.error('支付失败:', err);
                this.cancelOrder();
            }
        });
    },

    cancelOrder() {
        const orderId = this.data.paymentInfo.order_id; // 假设订单ID在 paymentInfo 中

        wx.request({
            url: `/api/orders/${orderId}/cancel`,
            method: 'POST',
            success: (res) => {
                if (res.statusCode === 200) {
                    console.log('订单取消成功:', res.data);
                    this.setData({
                        paymentInfo: null,
                        orderCancelInfo: '订单已取消'
                    });
                } else {
                    console.error('订单取消失败:', res.data);
                    this.setData({
                        orderCancelInfo: '订单取消失败'
                    });
                }
            },
            fail: (err) => {
                console.error('请求失败:', err);
                this.setData({
                    orderCancelInfo: '请求失败'
                });
            }
        });
    },
    getUserId() {
        // 实现获取用户ID的逻辑
        // 例如，从缓存中获取用户ID
        return wx.getStorageSync('userId');
    },

    handleSearch: function(e) {
        // 搜索逻辑不变
    },
    filterCourses: function(e) {
        const category = e.currentTarget.dataset.category;
        console.log('Selected category:', category); // 调试信息
        if (category && category.id) {
            this.setData({
                selectedCategory: category,
                courses: [] // 清空课程数据
            });
            this.getCourses(category); // 获取选中类别的课程数据
        } else {
            console.error('Invalid category object:', course); // 调试信息
        }
    },
    goToCourseDetails: function(e) {
        const course = e.currentTarget.dataset.course;
        console.log('Navigating to course details:', course); // 调试信息
        if (typeof course === 'object' && course !== null && course.category_id) {
            wx.navigateTo({
                url: `/pages/courseDetail/courseDetail?courseId=${course.id}&category_id=${course.category_id}`
            });
        } else {
            console.error('Invalid course object:', course); // 调试信息
            wx.showToast({
                title: '课程数据无效，请重试',
                icon: 'none'
            });
        }
    }
    
});